import Qt 4.7
import QtWebKit 1.0
import "config.js" as Options

Rectangle {
    id: window

    width: 1024
    height: 560
    state: "showSearch"

    Component.onCompleted: {
        bookmarkModel._get()
    }

    JSONModel {
        id: tagsModel
        path: "/tags"

        onLoaded: {
            clear();
            json.forEach(function(item) {
                append({value: item});
            })
        }
    }

    JSONModel {
        id: dialogsModel
        path: "/dialog_views"

        function bookmark(id) {
            var bookmark_index = bookmarkModel.find({dialogId: id})
            if(bookmark_index !== null) {
                var bookmark = bookmarkModel.get(bookmark_index)
            }
            return bookmark && bookmark.coupletId
        }



        onLoaded: {
            clear();
            json.slice(1).forEach(function(item) {
                append({id: item.dialogId, name: item.dialogName, "bookmark": bookmark(item.dialogId)});
            })
        }
        onError: {
            append({id: 1, name: "Sample questions", bookmark: 0});
        }
    }

    JSONModel {
        id: coupletsModel
        property int current: 0
        property int dialog_id

        function for_dialog(id) {
            id = id || 1;
            dialog_id = id
            var new_path = ("/qa_views/?dialog_Id=%i".replace("%i", id));
            if(new_path !== path) {
                current = -1
                clear()
                path = new_path
            }
            else {
                current = 0
            }
        }

        function rating(id) {
            var item = get(id)
            var rating_index = viewedModel.find({dialogId: dialog_id, coupletId: item.id})
            if(rating_index !== null) {
                var rating = viewedModel.get(rating_index)
            }
            return rating && rating.rating
        }

        function dialogName(dialogId) {
            var dialog_index = dialogsModel.find({id: dialogId})
            var dialog = dialogsModel.get(dialog_index)
            if(dialog_index === null) {
                return ""
            }
            return dialog.name
        }
        function getDialogIndex(){
            return dialog_id
        }

        onLoaded: {
            clear();
            current = -1
            json.slice(1).forEach(function(item) {
                append({question: item.question, answer: item.answer, id: item.id, groupId: item.qaGroup, groupPos: item.groupOrder, authorRating: item.authorRating, image: item.media});
            })
            couplet.reveal()
            var bookmark = dialogsModel.bookmark(coupletsModel.dialog_id)
            bookmark = find({id: bookmark})
            current = bookmark || couplet.selectCouplet()
        }
        onError: {
            append({id: 1, question: "Why is the network broken?", answer: "Murphy's Law"})
        }
    }

    JSONModel {
        id: viewedModel
        property int dialogId

        function viewedCouplet(dialog_id, couplet_id) {
            var item = firstOrCreate({dialogId: dialog_id, coupletId: couplet_id})
            var times_viewed = item.timesViewed || 0
            times_viewed += 1
            setProperty(item.index, "timesViewed", times_viewed)
        }

        function rateCouplet(dialog_id, couplet_id, rating) {
            var item = firstOrCreate({dialogId: dialog_id, coupletId: couplet_id})
            setProperty(item.index, "rating", rating)
        }


        function _get(dialog_id) {
            if(!authenticator.authenticated) {
//                return;
            }
            dialogId = dialog_id
            path = "/users_views/usersView/"
        }

        function post(dialog_id) {
            if(!authenticator.authenticated) {
//                return;
            }
            var objects = []
            for(var i = 0; i < count; i += 1) {
                var item = get(i);
                if(item.dialogId === dialog_id) {
                    objects.push({dialogId: item.dialogId, coupletId: item.coupletId, timesViewed: item.timesViewed, studentRating: item.rating})
                }
            }
            json = JSON.stringify(objects);
            _post("/users_views/usersView/")
        }

        onLoaded: {
             json.slice(1).forEach(function(item) {
                if(item.dialogId !== dialogId) {
                    continue;
                }
                var item = firstOrCreate({dialogId: dialogId, coupletId: item.coupletId})
                var timesViewed = item.timesViewed || 0
                timesViewed += item.timesViewed
                setProperty(item.index, "timesViewed", timesViewed)
                setProperty(item.index, "rating", item.studentRating)
            })
        }


    }

    JSONModel {
        id: bookmarkModel

        function setBookmark(dialog_id, couplet_id) {
            var item = firstOrCreate({dialogId: dialog_id})
            setProperty(item.index, "coupletId", couplet_id)
        }

        function _get() {
            if(!authenticator.authenticated) {
//                return;
            }
            path = "/users_views/usersBookmark/"
        }

        function post() {
            if(!authenticator.authenticated) {
//                return;
            }
            var object = []
            for(var i = 0; i < count; i += 1) {
                var item = get(i)
                if(item.dialogId === undefined || item.coupletId === undefined) {
                    continue
                }
                object.push({dialogId: item.dialogId, coupletId: item.coupletId});
            }
            json = JSON.stringify(object)
            _post("/users_views/usersBookmark/", authenticator.cookies)
        }

        onLoaded: {
             json.slice(1).forEach(function(item) {
                setBookmark(item.dialogId, item.coupletId)
            })
            for(var i = 0; i < dialogsModel.count; i += 1) {
                var item = dialogsModel.get(i);
                if(item.bookmark === undefined) {
                    dialogsModel.setProperty(i, "bookmark", dialogsModel.bookmark(item.id))
                }
            }
        }

    }

    Item {
        id: bigSearch
        anchors.fill: parent

        SearchField {
            id: bigSearchField
            model: tagsModel
            defaultText: "Search for Questions"
            height: 60
            width: 600
            anchors.centerIn: parent
            onSubmit: {
                dialogsModel.path = "/dialog_views?q=" + text
                window.state = "showDialogs"
                search.text = text
            }
        }
    }

    DialogList {
        id: dialogs

        anchors.top: title.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.bottom: parent.bottom

        onClicked: {
            coupletsModel.for_dialog(selected_dialog)
            window.state = "showCouplet"
        }
        model: dialogsModel
    }

    SingleCouplet {
        id: couplet
        model: coupletsModel

        onRevealed: {
            viewedModel.viewedCouplet(model.dialog_id, model.get(current).id)
            bookmarkModel.setBookmark(model.dialog_id, model.get(current).id)
        }

        onRatingChanged: {
            viewedModel.rateCouplet(model.dialog_id, model.get(current).id, rating)
        }
    }

    WebView {
        property bool authenticated: false
        property string username
        property string cookies

        id: authenticator
        anchors.fill: parent

        onLoadFailed: {
            console.log("failed")
        }

        onLoadFinished: {
            var body = evaluateJavaScript('document.body.innerHTML')
            var return_cookies = evaluateJavaScript('document.cookie')
            var match = body.match(/^WELCOME user (\w+).$/)
            if(match) {
                authenticated = true
                username = match[1]
                cookies = return_cookies
                window.state = "showDialogs"
                bookmarkModel._get()
            }
        }
    }

    Rectangle {
        id: title
        width: parent.width
        height: 40

        SearchField {
            id: search
            model: tagsModel
            defaultText: "search..."
            anchors.top: parent.top
            onSubmit: {
                dialogsModel.path = "/dialog_views?q=" + text
            }
        }

        Button {
            id: authenticateBtn
            text: "Login"
            anchors.top: parent.top
            anchors.right: parent.right
            onClicked: {
                window.state = "showLogin"
            }
            visible: authenticator.username === ""
        }

        Text {
            text: authenticator.username
            anchors.top: parent.top
            anchors.right: parent.right
        }

        Rectangle {
            border.width: 1
            border.color: "#000000"
            height: 1
            width: parent.width
            anchors.bottom: parent.bottom
            radius: 1
        }
    }

    states: [
        State {
            name: "showCouplet"
            PropertyChanges { target: title; visible: false }
            PropertyChanges { target: dialogs; visible: false }
            PropertyChanges { target: couplet; visible: true }
            PropertyChanges { target: authenticator; visible: false }
            PropertyChanges { target: bigSearch; visible: false }

            StateChangeScript {
                script: {
                    couplet.reveal()
                    var bookmark = dialogsModel.bookmark(coupletsModel.dialog_id)
                    var couplet_index = coupletsModel.find({id: bookmark})
                    coupletsModel.current = couplet_index || couplet.selectCouplet()
                }
            }
        },
        State {
            name: "showLogin"
            PropertyChanges { target: title; visible: false }
            PropertyChanges { target: dialogs; visible: false }
            PropertyChanges { target: couplet; visible: false }
            PropertyChanges { target: authenticator; visible: true }
            PropertyChanges { target: bigSearch; visible: false }

            StateChangeScript {
                script: {
                    var server = Options.server || "http://127.0.0.1"
                    authenticator.url = server + "/accounts/login"
                }
            }
        },
        State {
            name: "showDialogs"
            PropertyChanges { target: title; visible: true }
            PropertyChanges { target: dialogs; visible: true }
            PropertyChanges { target: couplet; visible: false }
            PropertyChanges { target: authenticator; visible: false }
            PropertyChanges { target: bigSearch; visible: false }

            StateChangeScript {
                script: {
                    if(coupletsModel.count === 0) {
                        return
                    }
                    bookmarkModel._get()
                    dialogsModel.reload()
                    bookmarkModel.post()
                    if(coupletsModel.dialog_id !== undefined) {
                        viewedModel.post(coupletsModel.dialog_id)
                    }
                }
            }
        },
        State {
            name: "showSearch"
            PropertyChanges { target: title; visible: false }
            PropertyChanges { target: dialogs; visible: false }
            PropertyChanges { target: couplet; visible: false }
            PropertyChanges { target: authenticator; visible: false }
            PropertyChanges { target: bigSearch; visible: true }

        }
    ]
}
